﻿using NewsReaderApp.ViewModels;
using NewsReaderApp.Views;
using NewsReaderApp.Views.SettingsPopups;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media.Animation;

namespace NewsReaderApp.Settings
{
    public static class SettingsCommandIDS
    {
        public const string PrivacyPolicy = "PrivacyPolicyID";
        public const string Settings = "SettingsID";
    }

    internal static class AppSettings
    {
        // Desired width for the settings UI. UI guidelines specify this should be 346 or 646 depending on your needs.
        private static double PRIVACY_POLICY_WIDTH = 346;
        private static double SETTINGS_WIDTH = 346;

        private static readonly List<Popup> s_popups = new List<Popup>();

        // Used to determine the correct height to ensure our custom UI fills the screen.
        //private static Rect s_windowBounds;

        public static void RegisterSettings()
        {
            // Listening for this event lets the app initialize the settings commands and pause its UI until the user closes the pane.
            // To ensure your settings are available at all times in your app, place your CommandsRequested handler in the overridden
            // OnWindowCreated of App.xaml.cs
            SettingsPane.GetForCurrentView().CommandsRequested += HandleCommandsRequested;
        }
        /// <summary>
        /// This event is generated when the user opens the settings pane. During this event, append your
        /// SettingsCommand objects to the available ApplicationCommands vector to make them available to the
        /// SettingsPange UI.
        /// </summary>
        /// <param name="settingsPane">Instance that triggered the event.</param>
        /// <param name="eventArgs">Event data describing the conditions that led to the event.</param>
        private static void HandleCommandsRequested(SettingsPane settingsPane, SettingsPaneCommandsRequestedEventArgs eventArgs)
        {

            List<SettingsCommand> l = new List<SettingsCommand>() {
              new SettingsCommand(SettingsCommandIDS.PrivacyPolicy, "Privacy Policy", HandleSettingsPopup),
              new SettingsCommand(SettingsCommandIDS.Settings , "Settings", HandleSettingsPopup)
            };

            foreach (var c in l)
            {
                eventArgs.Request.ApplicationCommands.Add(c);
            }
        }

                /// <summary>
        /// We use the window's activated event to force closing the Popup since a user maybe interacted with
        /// something that didn't normally trigger an obvious dismiss.
        /// </summary>
        /// <param name="sender">Instance that triggered the event.</param>
        /// <param name="e">Event data describing the conditions that led to the event.</param>
        private static void OnWindowActivated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        {
            if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
            {
                foreach (var popup in s_popups)
                {
                    popup.IsOpen = false;
                }
            }
        }
                /// <summary>
        /// When the Popup closes we no longer need to monitor activation changes.
        /// </summary>
        /// <param name="sender">Instance that triggered the event.</param>
        /// <param name="e">Event data describing the conditions that led to the event.</param>
        private static void OnPopupClosed(object sender, object e)
        {
            Window.Current.Activated -= OnWindowActivated;

            var control = sender as Popup;
            if (control != null)
            {
                var pg = control.Child as Page;
                if (pg != null)
                {
                    var appyable = pg.DataContext as IApplyable;
                    if (appyable != null)
                    {
                        appyable.Apply();
                    }
                }
            }


        }

        public static void HandleSettingsPopup(IUICommand command)
        {
            var bounds = Window.Current.Bounds;
            //    // Create a Popup window which will contain our flyout.
            var popup = new Popup();
            popup.Closed += OnPopupClosed;

            Window.Current.Activated += OnWindowActivated;
            popup.IsLightDismissEnabled = true;
            popup.Height = bounds.Height;

            // Add the proper animation for the panel.
            popup.ChildTransitions = new TransitionCollection();
            popup.ChildTransitions.Add(new PaneThemeTransition()
            {
                Edge = (SettingsPane.Edge == SettingsEdgeLocation.Right) ?
                   EdgeTransitionLocation.Right :
                   EdgeTransitionLocation.Left
            });

            Page pane = null;
            double popupWidth = 0;
            switch ((string)command.Id)
            {
                case SettingsCommandIDS.PrivacyPolicy:
                    popupWidth = PRIVACY_POLICY_WIDTH;
                    pane = new PrivacyPolicyPage();
                    break;
                case SettingsCommandIDS.Settings:
                    popupWidth = SETTINGS_WIDTH;
                    pane = new SettingsPage();
                    pane.DataContext = new SettingsViewModel();
                    break;
            }

            popup.Width = popupWidth;
            // Let's define the location of our Popup.
            popup.SetValue(Canvas.LeftProperty, SettingsPane.Edge == SettingsEdgeLocation.Right ?
                (bounds.Width - popupWidth) : 0);
            pane.Width = popupWidth;
            pane.Height = bounds.Height;
            
            // Place the SettingsFlyout inside our Popup window.
            popup.Child = pane;
            popup.SetValue(Canvas.TopProperty, 0);
            popup.IsOpen = true;
            
            s_popups.Add(popup);
        }
    }
}
